<template>
  <div>
    <!-- 数据表格 -->
    <PageTable
      :loading="loading"
      :data="dataSource"
      :columns="columns"
      :options="options"
      @selectChange="selectChange"
    />
    <Pagination
      v-show="total > 0"
      :total="total"
      :pageNo.sync="listQuery.pageNo"
      :pageSize.sync="listQuery.pageSize"
      @pagination="handleList"
    />
    <exchange-record-dialog
      ref="exchangeRecord"
      :exchangeRecordFlag.sync="exchangeRecordFlag"
      v-if="exchangeRecordFlag"
    ></exchange-record-dialog>
  </div>
</template>

<script>
import ExchangeRecordDialog from '@/views/integral/integral-settlement/components/exchangeRecordDialog'
import { export2Excel } from '@/utils/export'
import { deepClone } from '@/utils'
export default {
  name: 'integralSupportTable',
  components: { ExchangeRecordDialog },
  data() {
    return {
      exchangeRecordFlag: false,
      sourceType: {
        10: '订单支付',
        11: '订单退款',
        12: '订单取消返还',
        13: '订单评价赠送积分',
        20: '企业主扫码赠送',
        21: '企业主定向赠送',
        22: '企业主分享链接赠送',
        30: '后台调整减少',
        31: '后台调整增加',
        40: '平台兑换（酒馆长）',
        41: '平台兑换（挖咖）',
        42: '平台兑换（机咖）',
        43: '平台兑换（秦宗）',
        44: '平台兑换（机甲通）',
        50: '礼品券扫码赠送',
        60: '平台新人注册赠送积分'
      },
      platform: {
        2: '好物特工',
        4: '酒馆长',
        8: '挖咖',
        16: '机咖',
        32: '秦宗',
        64: '机甲通'
      },
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      loading: false,
      options: {
        border: true,
        select: true
      },
      selectList: [],
      tabs: [
        { label: '好物平台', num: '', key: 'integral', value: 2 },
        { label: '秦宗平台', num: '', key: 'repast', value: 32 },
        { label: '酒馆长平台', num: '', key: 'tavern', value: 4 },
        { label: '机咖平台', num: '', key: 'jika', value: 16 },
        { label: '挖咖平台', num: '', key: 'waka', value: 8 }
      ],
      // 表格列
      columns: [
        { prop: 'id', label: 'ID' },
        {
          prop: 'oriAmount',
          label: '原平台积分值',
          render: (h, { row }) => {
            return <div>{row.oriAmount || 0}</div>
          }
        },
        {
          prop: 'amount',
          label: '入账后积分值',
          render: (h, { row }) => {
            return <div>{row.amount || 0}</div>
          }
        },
        {
          props: 'integralType',
          label: '积分类型',
          render: () => {
            return <div>支入</div>
          }
        },
        {
          prop: 'availableBalance',
          label: '账户余额',
          render: (h, { row }) => {
            return <div>{row.availableBalance || 0}</div>
          }
        },
        {
          prop: 'changeType',
          label: '来源类型',
          render: (h, { row }) => {
            return <div>{this.sourceType[row.changeType]}</div>
          }
        },
        {
          prop: 'description',
          label: '积分描述',
          render: (h, { row }) => {
            return (
              <div>
                <div>
                  {[20, 21, 22, 50].includes(row.changeType) ? (
                    <p>{row.description}</p>
                  ) : (
                    <p>{this.sourceType[row.changeType]}</p>
                  )}
                </div>
                {[20, 21, 22].includes(row.changeType) && (
                  <el-popover
                    placement="top-start"
                    title="积分赠送备注"
                    width="200"
                    trigger="click"
                  >
                    <div className="mb-10">{row.remark}</div>
                    <div
                      className="handel flex justify-between"
                      style="padding-top: 10px;border-top: 1px solid #eee"
                    >
                      <p>操作人：{row.createdUser}</p>
                      <p>时间：{row.updatedTime}</p>
                    </div>
                    <el-button slot="reference" underline={false} type="text">
                      查看备注
                    </el-button>
                  </el-popover>
                )}
                {row.changeType === 50 && (
                  <el-button type="text" onClick={() => this.handleViewRecord(row)}>
                    查看记录
                  </el-button>
                )}
                {[10, 11, 12, 13].includes(row.changeType) && (
                  <el-button type="text" onClick={() => this.handleViewOrder(row)}>
                    查看订单
                  </el-button>
                )}
              </div>
            )
          }
        },
        {
          prop: 'platform',
          label: '积分来源',
          render: (h, { row }) => {
            return <div>{this.platform[row.platform]}</div>
          }
        },
        {
          prop: 'createdTime',
          label: '操作时间',
          render: (h, { row }) => {
            return <div>{row.createdTime || '暂无'}</div>
          }
        },
        { prop: 'ip', label: 'ip地址' },
        {
          prop: 'recordStatus',
          label: '状态',
          render: (h, { row }) => {
            return (
              <div>
                <p style={row.recordStatus === 2 ? 'color:#fc4541' : ''}>
                  {row.recordStatus === 1 ? '成功' : '失败'}
                </p>
              </div>
            )
          }
        }
      ],
      dataSource: [],
      params: {}
    }
  },
  created() {},
  methods: {
    handleList() {
      this.handleIntegralList(this.params)
    },
    // 积分兑换记录
    async handleIntegralList(obj) {
      this.params = deepClone(obj)
      delete this.params.type
      if (obj.type) this.listQuery.pageNo = 1
      const params = {
        ...this.listQuery,
        ...obj
      }
      console.log(params)
      const {
        data: { records, total }
      } = await this.$http.integral.integralSettlementApi.getIntegralList(params)
      this.total = total
      this.dataSource = records
    },
    // 查看记录
    handleViewRecord(row) {
      this.exchangeRecordFlag = true
      this.$nextTick(() => {
        this.$refs.exchangeRecord.initData(row.userId, row.platform, row.transactionType)
      })
    },

    //查看订单
    async handleViewOrder(row) {
      const { data, status, msg } = await this.$http.integral.integralSettlementApi.getRefundOrder(
        row.changeNo
      )
      if (status === 200) {
        await this.$router.push({ name: 'OrderDetail', query: { orderNo: data.orderNo } })
      } else {
        this.$message.warning(msg)
      }
    },
    // 积分兑换选择
    selectChange(value) {
      this.selectList = value
    },

    //导出
    async exportFile(type, obj) {
      if (type === 'part') {
        if (!this.selectList.length) return this.$message.error('请选择要导出的数据！')
        const title = this.tabs.find(item => item.value === obj.platform)?.label
        this.handleExport(this.selectList, title)
      }
      if (type === 'all') {
        for (const item of this.tabs) {
          const title = item.label
          const params = {
            pageNo: 1,
            pageSize: 1000,
            ...obj,
            platform: item.value
          }
          const {
            data: { records }
          } = await this.$http.integral.integralSettlementApi.getIntegralList(params)
          if (records.length) this.handleExport(records, title)
        }
      }
    },

    handleExport(selectList, title) {
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      const list = this.$lodash.cloneDeep(selectList)
      const tableData = list.map(item => {
        item.integralType = '支入'
        item.recordStatus = item.recordStatus === 1 ? '成功' : '失败'
        item.platform = this.platform[item.platform]
        item.availableBalance = item.availableBalance || 0
        item.amount = item.amount || 0
        item.oriAmount = item.oriAmount || 0
        item.description = [20, 21, 22, 50].includes(item.changeType)
          ? item.description
          : this.sourceType[item.changeType]
        item.changeType = this.sourceType[item.changeType]
        return item
      })
      export2Excel(headerData, tableData, filterData, `积分核算对账单-${title}支入明细`, () => {
        this.$message.success('导出成功')
      })
    }
  }
}
</script>

<style scoped></style>
